import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
public class Main {
    public static void generateQRCode(String url, int width, int height, String filePath) {
        try {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.MARGIN, 1); // 设置边距
            BitMatrix bitMatrix = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, width, height, hints);
            Path path = FileSystems.getDefault().getPath(filePath);
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
            System.out.println("二维码生成成功，保存路径：" + filePath);
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String url = "https://www.example.com"; // 要生成二维码的URL
        int width = 300; // 二维码宽度
        int height = 300; // 二维码高度
        String filePath = "QRCode.png"; // 保存路径
        generateQRCode(url, width, height, filePath);
    }
}